package com.init.service.impl;


import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Set;

/**
 * LFU缓存淘汰
 *
 * @author Atanycosts
 * @Data 2024/5/9
 */
@Service
public class LFUCacheService {

    private static final String LFU_SET = "LFU_SET";

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    public void updateAccessFrequency(String key) {

        // 增加访问次数
        stringRedisTemplate.opsForZSet().incrementScore(LFU_SET, key, 2.0);

    }

    public void evictLFUItem() {
        // 获取访问次数最少的key 分数不超过1.0的元素
        Set<String> keys = stringRedisTemplate.opsForZSet().rangeByScore(LFU_SET, Double.NEGATIVE_INFINITY, 1.0);
        if (keys != null && !keys.isEmpty()) {
            String keyToEvict = keys.iterator().next();
            // 删除sorted set中的key
            stringRedisTemplate.opsForZSet().remove(LFU_SET, keyToEvict);
            // 从实际缓存中移除对应的数据
            stringRedisTemplate.delete(keyToEvict);
        }
    }
}